const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

//ajax请求
const getApi = (config) => {
  // data, action, func, text
  return new Promise((resolve,reject)=>{
    let text = config.text || 'YES';
    if (text == 'YES') {
      wx.showLoading({
        title: '正在加载中...',
      })
    }else{
      wx.showLoading({
        title: text,
      })
    }
    wx.request({
      url: 'https://www.cqymzp.top/gateway/api' + config.action,  //http://47.113.107.90
      method: config.method || 'GET',
      data: config.data,
      header: {
        'content-type': 'application/json',
        Authorization: 'Bearer ' + wx.getStorageSync('token')
      },
      success: function (res) {
        wx.hideLoading();
        resolve(res.data)
      }
    })
  })

}

const urlDecode = (str) => {
  var ret = "";
  for (var i = 0; i < str.length; i++) {
    var chr = str.charAt(i);
    if (chr == "+") {
      ret += " ";
    } else if (chr == "%") {
      var asc = str.substring(i + 1, i + 3);
      if (parseInt("0x" + asc) > 0x7f) {
        ret += asc2str(parseInt("0x" + asc + str.substring(i + 4, i + 6)));
        i += 5;
      } else {
        ret += asc2str(parseInt("0x" + asc));
        i += 2;
      }
    } else {
      ret += chr;
    }
  }
  return ret;
}

const asc2str = (ascasc) => {
  return String.fromCharCode(ascasc);
}

module.exports = {
  formatTime: formatTime,
  getApi: getApi,
  urlDecode: urlDecode
}
